<template>
  <div class="app-container">
    <div class="app-tree-container">
      <left-tree-select
        ref="leftTreeSelectRef"
        :title="`${t('button.fileList')}`"
        :treeData="helperDocList"
        iconName="documentation"
        :treeProps="{
          children: 'children',
          label: 'fileName',
        }"
        :needRightBtn="false"
        :selectProps="{
          children: 'children',
          label: 'fileName',
          value: 'id',
        }"
        :selectOption="selectDocOption"
        nodeKeyField="id"
        @handleNodeClick="handeTempClick"
      >
        <template v-slot:titleBTn>
          <AshUpload
            :file-type="'.pdf'"
            :btnText="`${t('button.fileUpload')}`"
            :limit="1"
            :multiple="false"
            :tip-show="false"
            @upload-success="uploadFiles"
          />
          <!-- </el-link> -->
        </template>
      </left-tree-select>

      <div class="right_table_area">
        <MobilePdfViewer
          v-if="isMobile"
          :url="pdfBlobUrl"
          :pdfBlob="pdfBlob"
        ></MobilePdfViewer>
        <div v-else class="table_center_area" id="pdfContainer" ref="pdfContainer"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { proxy } = getCurrentInstance();
import MobilePdfViewer from "./components/MobilePdfViewer.vue";
import AshUpload from "@/components/AshUpload";
import * as pdfjsLib from "pdfjs-dist";
import { PDFViewer } from "pdfjs-dist/web/pdf_viewer";

// 设置 Worker 的路径
pdfjsLib.GlobalWorkerOptions.workerSrc = "/pdf.worker.mjs";
import colors from "@/assets/styles/variables.module.scss";
import { Edit, Document } from "@element-plus/icons-vue";
import LeftTreeSelect from "@/components/AshCommon/LeftTreeSelect.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getUserInfo } from "@/utils/auth";
import {
  GetHelperDocList,
  UploadHelperDoc,
  GetHelperDocDetail,
} from "@/api/docManage/helperDoc";
import useAppStore from "@/store/modules/app";
// import TopForm from "./components/topForm.vue";
import { nextTick } from "vue";
const appStore = useAppStore();
const operateSysId = computed(() => import.meta.env.VITE_APP_SYS_ID);
const helperDocList = ref([]);
const pdfContainer = ref(null); //预览pdf 内容
const loadingPdf = ref(false);
const pdfBlobUrl = ref("");
const selectDocOption = ref({});
const loading = ref(false);
const leftTreeSelectRef = ref(null);
const statisDetailInfo = ref({}); //详情数据,筛选出数据列和字段列

const uploadParams = ref({
  systemId: "",
  operatingUserId: "",
  operatingUserName: "",
  helpFile: null,
});

const pdfBlob = ref(null); //blob数据
const isMobile = ref(false);

function checkIsMobile() {
  isMobile.value =
    /Mobi|Android|iPhone|iPad|iPod/i.test(navigator.userAgent) ||
    window.innerWidth <= 800;
}

//上传资产
async function uploadFiles(fileList) {
  const params = {
    operatingUserId: JSON.parse(getUserInfo()).userId,
    operatingUserName: JSON.parse(getUserInfo()).userName,
    helpFile: fileList,
    systemId: operateSysId.value,
  };
  try {
    const res = await UploadHelperDoc(params);
    ElMessage({ message: t("message.uploadSuccess"), type: "success" });
    await queryDocList();
  } catch (error) {
    console.error("上传失败", error);
  }
}

//点击树结构
async function handeTempClick(e) {
  selectDocOption.value = JSON.parse(JSON.stringify(e));
  // dymicData.value = [];
  try {
    const res = await queryTempDetail(e.fileName);
    const blob = new Blob([res], { type: "application/pdf" });
    await loadPdf(blob);
  } catch (error) {
    console.log("错误", error);
  }
}

function loadPdf(blob) {
  pdfBlob.value = blob; // 测试用的blob数据
  const blobUrl = URL.createObjectURL(blob);
  pdfBlobUrl.value = blobUrl;

  // 检查是否为移动设备
  if (isMobile.value) {
  } else {
    if (pdfContainer.value) {
      pdfContainer.value.innerHTML = "";
      const iframe = document.createElement("iframe");
      iframe.src = blobUrl;
      iframe.style.width = "100%";
      iframe.style.height = "100%";
      iframe.style.border = "1px solid #000";
      iframe.style.overflowY = "auto";
      pdfContainer.value.appendChild(iframe);
    }
  }
}

function queryTempDetail(fileName) {
  return new Promise((resolve, reject) => {
    const params = {
      systemId: operateSysId.value,
      fileName: fileName,
    };
    GetHelperDocDetail(params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

//获取统计模板
function queryDocList() {
  GetHelperDocList(operateSysId.value)
    .then((res) => {
      helperDocList.value = res.output.map((item, index) => ({
        ...item,
        id: index,
      }));
    })
    .catch((err) => {
      helperDocList.value = [];
    });
}

watch(
  () => helperDocList.value,
  (newVal) => {
    if (leftTreeSelectRef.value && newVal.length > 0) {
      const firstNodeKey = newVal[0]["id"];

      nextTick(() => {
        proxy.$refs.leftTreeSelectRef.leftTreeSelectRef.setCurrentKey(firstNodeKey); // 高亮第一个节点
        proxy.$refs.leftTreeSelectRef.leftTreeSelectRef.setCheckedKeys([firstNodeKey]); // 选中第一个节点
      });
      // 模拟点击事件，调用 handleNodeClick 方法
      const firstNodeData = newVal[1]; // 假设这是我们要传递的节点数据
      handeTempClick(firstNodeData); // 模拟点击，执行点击后的查询操作
    }
  },
  { deep: true }
);

onUnmounted(() => {
  window.removeEventListener("resize", checkIsMobile);
});
onMounted(() => {
  queryDocList();
  checkIsMobile(); // 初始判断
  window.addEventListener("resize", checkIsMobile);
});
</script>

<style lang="scss" scoped>
.table_center_area {
  height: 100% !important;
  .table_main {
    height: calc(100% - 180px) !important;
  }
}

canvas {
  display: block;
  margin: 0 auto 20px auto;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
}
@media (max-width: 768px) {
  .app-tree-container .right_table_area {
    margin-top: 20px;
  }
}
</style>
